package middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/unrolled/secure"
)

// CrossDomain http跨域处理
func CrossDomain() gin.HandlerFunc {
	return func(c *gin.Context) {
		origin := c.Request.Header.Get("Origin")
		if origin == "" {
			origin = "*"
		}
		// 设置允许访问的域
		c.Header("Access-Control-Allow-Origin", origin)
		c.Header("Vary", "Origin")
		// 服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
		// header的类型
		c.Header("Access-Control-Allow-Headers", c.Request.Header.Get("Access-Control-Request-Headers"))
		// 跨域关键设置 让浏览器可以解析
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
		// 本次预检请求的有效期，设置为24小时
		c.Header("Access-Control-Max-Age", "86400")
		// 跨域请求是否需要带cookie信息 设置为true
		c.Header("Access-Control-Allow-Credentials", "true")
		// 设置返回格式是json
		//c.Set("content-type", "application/json")
		// 预请求回应
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
			return // 直接返回,不继续往下执行
		}
		// next之前请求拦截
		c.Next()
		// next之后响应拦截
	}
}

// TLSHandler .
func TLSHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		secureMiddleware := secure.New(secure.Options{
			SSLRedirect: true,
			SSLHost:     "localhost:3000",
		})
		err := secureMiddleware.Process(c.Writer, c.Request)

		// If there was an error, do not continue.
		if err != nil {
			return
		}

		c.Next()
	}
}
